import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:flutter/foundation.dart';

import 'package:dio/dio.dart';

import '../jzx_apps.dart';
import '../services/jzx_app.dart';
import '../services/jzx_user.dart';

/// 请求拦截相关的处理
class JzxNetInterceptor extends Interceptor {
  JzxNetInterceptor();

  final _kSuccessCode = 0;
  final _kTokenExpireCode = 10010303;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    final headers = options.headers;

    headers['device-id'] =
        JzxAppService.to.device.identifier; // 设备id或者udid，保证当前设备唯一值。
    if (Platform.isAndroid) {
      headers['platform'] = 'Android';
      headers['model'] = JzxAppService.to.device.model; // 设备型号
    } else if (Platform.isIOS) {
      headers["platform"] = "iOS";
      headers['model'] = JzxAppService.to.device.model; // 设备型号
    }
    headers['pkg'] = JzxAppService.to.packageInfo?.packageName; // 包名
    headers['ver'] =
        JzxAppService.to.packageInfo?.version; // 版本 例如1.0.0，读取实际配置的版本号
    headers['p_ver'] =
        JzxAppService.to.packageInfo?.buildNumber; // build number
    headers['kst'] = '1'; // 固定传1
    headers['sys_lan'] = Get.locale?.languageCode; // 手机系统语言 如英文en
    headers['lang'] = Get.locale?.languageCode; // 手机系统语言 如英文en

    final token = JzxUserService.to.tokenData.token;
    if (token.isNotEmpty) {
      // options.headers['Blade-Auth'] = token;
      headers['Authorization'] = 'Bearer$token';
    }
    // options.headers = headers;

    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    _printResponse(response);
    Map dataMap;
    if (response.data is Map) {
      // 解决没有code返回的情况
      if (response.data['success'] == 'true' && response.data['code'] == null) {
        response.data['code'] == _kSuccessCode;
      }
      dataMap = response.data;
    } else if (response.data is String) {
      dataMap = jsonDecode(response.data);
    } else {
      dataMap = {
        'code': _kSuccessCode,
        'data': response.data,
        'msg': 'success'
      };
    }

    /// 优先处理请求成功
    if (dataMap['code'] == _kSuccessCode || '${dataMap['success']}' == 'true') {
      /// 请求成功的异常
      if (dataMap['data'] is Map && dataMap['data']['error_code'] != null) {
        final message = dataMap['data']['error_description'] ?? '返回结果错误';
        handler.reject(
          DioException(
            requestOptions: response.requestOptions,
            error: message,
          ),
          true,
        );
        JzxToast.hideLoading();
        JzxToast.message(message);
        return;
      }
      if (dataMap['code'] == _kSuccessCode) {
        response.data = dataMap['data'] ?? {};
      } else {
        // 状态码为其他值，且需要返回数据
        response.data = dataMap;
      }
      handler.next(response);
      return;
    }

    // // 状态码为其他值，且需要返回数据
    // final specialCode = [260, 261, 262].contains(dataMap['code']);
    // // final specialUrl = response.realUri.path.contains('/articleDetail');

    // if (specialCode) {
    //   // 状态码为其他值，且需要返回数据
    //   response.data = dataMap;
    //   handler.next(response);
    //   return;
    // }

    // 通用异常处理
    if (dataMap['code'] == _kTokenExpireCode) {
      // AppService.bus.fire(AppNeedToLogin());
      if ('${dataMap['msg']}'.isNotEmpty) {
        showMessage(dataMap['msg'], onDissmiss: () {
          JzxUserService.to.logout();
        });
      } else {
        JzxUserService.to.logout();
      }
      return;
    }

    // 错误处理
    handler.reject(
      DioException(
        requestOptions: response.requestOptions,
        error: dataMap['msg'],
      ),
      true,
    );
    JzxToast.hideLoading();
    JzxToast.message(dataMap['msg']);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    super.onError(err, handler);
    debugPrint('onError ------------ ${err.response}');
  }
}

void _printResponse(Response response) {
  // final path = response.requestOptions.uri.path;
  // final tag = path.split('?').first;
  log('''
------------------------ 输出响应数据 - 开始 ------------------------
url = ${response.requestOptions.uri}
method = ${response.requestOptions.method}
headers = ${response.requestOptions.headers}
queryParameters = ${response.requestOptions.queryParameters}
requestData = ${response.requestOptions.data}
responseData = ${response.toString()},
------------------------ 输出响应数据 - 结束 ------------------------
''');
}
